package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;

import models.beans.Conta;
import models.beans.User;

public class ContaDAO {
	private Connection con;
	private PreparedStatement pstmt;
	
	public ContaDAO() {
		con = DAO.getInstance().getConnection();
	}
	
	public boolean cadastraAcc(Conta conta){
		try {
			pstmt = con.prepareStatement("INSERT INTO Contas(login, senha, isAdm) VALUES(?, ?, ?)");
		
			pstmt.setString(1, conta.getLogin());
			pstmt.setString(2, conta.getSenha());
			pstmt.setBoolean(3, conta.isAdm());
			
			return pstmt.execute();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	public boolean logar(Conta c) throws SQLException{
		pstmt = con.prepareStatement("SELECT COUNT(idConta) AS conta FROM Contas WHERE login = ? AND senha = ?");
		
		pstmt.setString(1, c.getLogin());
		pstmt.setString(2, c.getSenha());

		ResultSet rs = pstmt.executeQuery();
		
		int conta = 0;
		while(rs != null && rs.next()){
			conta = Integer.parseInt(rs.getString("conta"));
		}
		
		System.out.println(conta);
		if(conta > 0) return true;
		
		return false;
	}
	
	public int getIdConta(Conta c){
		try {
			pstmt = con.prepareStatement("SELECT idConta FROM Contas WHERE login = ? AND senha = ?");
		
			pstmt.setString(1, c.getLogin());
			pstmt.setString(2, c.getSenha());
			
			ResultSet rs = pstmt.executeQuery();
			
			int id = -1;
			while(rs.next()){
				id = rs.getInt(1);
			}
			
			return id;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return -1;
	}
	
}
